<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolBar" style="float:left;padding-top: 10px;padding-left: 50px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-form-item prop="shop">
          <el-select v-model="filters.shop" :clearable="true" placeholder="店铺" style="width: 10em">
            <el-option v-for="item in shops"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsType">
          <el-select v-model="filters.goodsType" clearable filterable placeholder="品类" style="width: 11em">
            <el-option v-for="item in goodsTypes"
                       :key="item.label"
                       :label="item.value"
                       :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="sku">
          <el-input v-model="filters.sku" placeholder="SKU" style="width: 10em"></el-input>
        </el-form-item>
        <el-form-item prop="tradeDateRange">
          <el-date-picker
            style="width: 20em"
            v-model="filters.tradeDateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-search"
                     :label="$t('action.search')"
                     perms="finance:revenue:goods"
                     @click="findPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-refresh"
                     :label="$t('action.reset')"
                     perms="finance:revenue:goods"
                     @click="reset"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-filter"
                     label="列显示"
                     perms="finance:revenue:goods"
                     @click="displayFilterColumnDialog"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="el-icon-download"
                     label="导出"
                     perms="finance:revenue:goods"
                     @click="exportGoodsRevenue"/>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>

    <!--表格内容栏-->
    <kt-table :data="pageResult" :columns="filterColumns" :execSummary="true" @findPage="findPage"></kt-table>

    <!--说明-->
    <div class="toolBar" style="padding-top: 35px">
      <p align="left"><b>总收入：</b>对亚马逊销售订单的product_sales列进行汇总的金额</p>
      <p align="left"><b>毛收入：</b>对亚马逊销售订单的total列进行汇总的金额，该项已经抵扣佣金、配送费、各种税费等</p>
      <p align="left"><b>毛利润：</b>毛收入 - (广告费用+仓储费用+退款费用+预估采购成本+预估包装成本+预估头程+广告成本)</p>
      <p align="left"><b>退款：</b>对亚马逊退款订单的total列进行汇总的金额，该项已经抵扣佣金、配送费等各项费用，是卖家承担退款的净损失金额</p>
      <p align="left"><b>预估头程：</b>(销售数量-退款数量) * SKU配置的头程成本单价</p>
      <p align="left"><b>采购成本：</b>(销售数量-退款数量) * 产品配置的采购成本单价</p>
      <p align="left"><b>包装成本：</b>(销售数量-退款数量) * 产品配置的包装成本单价</p>
      <p align="left"><b>广告占比：</b>广告成本/总收入</p>
    </div>
  </div>
</template>

<script>
  import KtTable from '../core/KtTable'
  import KtButton from '../core/KtButton'
  import TableColumnFilterDialog from '../core/TableColumnFilterDialog'

  export default {
    name: "Goods",
    components: {
      KtTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        size: 'small',
        filters: {
          shop: '',
          goodsTypes: [
            {label: 'normal', value: '常规品类'}
          ],
          sku: '',
          tradeDateRange: [],
        },
        //初始表格列显示字段
        columns: [],
        //列显示过滤字段
        filterColumns: [],
        pageRequest: {},
        pageResult: {},
        shops: [],
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '本月至今',
              onClick(picker) {
                const start = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
                const end = new Date();
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }]
        }
      }
    },
    methods: {
      // 处理表格列过滤显示
      initColumns() {
        this.columns = [
          {prop: "shop", label: "店铺", minWidth: 80},
          {prop: "sku", label: "SKU", minWidth: 120},
          {prop: "tradeMonth", label: "月份", sortable: true, minWidth: 80},
          {prop: "productSales", label: "总收入(￥)", sortable: true, minWidth: 110, formatter: true},
          {prop: "saleRevenue", label: "毛收入(￥)", sortable: true, minWidth: 110, formatter: true},
          {prop: "netProfit", label: "毛利润(￥)", sortable: true, minWidth: 110, formatter: true},
          {prop: "saleQuantity", label: "销量(件)", sortable: true, minWidth: 100},
          {prop: "returnFee", label: "退款(￥)", sortable: true, minWidth: 100, formatter: true},
          {prop: "returnQuantity", label: "退货(件)", sortable: true, minWidth: 100},
          {prop: "returnRatio", label: "退货率", sortable: true, minWidth: 100},
          {prop: "advertiseFee", label: "广告成本(￥)", sortable: true, minWidth: 120, formatter: true},
          {prop: "advertiseRatio", label: "广告占比", sortable: true, minWidth: 120, formatter: true},
          {prop: "lastMonthStorageFee", label: "上个月仓储费(￥)", sortable: true, minWidth: 150, formatter: true},
          {prop: "purchaseFee", label: "采购成本(￥)", sortable: true, minWidth: 120, formatter: true},
          {prop: "packFee", label: "包装成本(￥)", sortable: true, minWidth: 120, formatter: true},
          {prop: "sellingFee", label: "平台佣金(￥)", sortable: true, minWidth: 120, formatter: true},
          {prop: "fbaFee", label: "配送费(￥)", sortable: true, minWidth: 110, formatter: true},
          {prop: "fbaProportion", label: "FBA占比", sortable: true, minWidth: 110, formatter: true},
          {prop: "headwayFee", label: "预估头程(￥)", sortable: true, minWidth: 120, formatter: true},
          {prop: "goodsTypeDesc", label: "品类", sortable: true, minWidth: 120, formatter: true},
        ];
        this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      },
      //处理表格列过滤显示
      displayFilterColumnDialog() {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns(data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      //获取分页数据
      findPage(data) {
        if ((data !== null && typeof data !== 'undefined') && typeof data.pageRequest !== 'undefined') {
          this.pageRequest = data.pageRequest;
        }
        //如果清空日期选择器，则会将tradeDateRange置为null
        if (this.filters.tradeDateRange === null) {
          this.filters.tradeDateRange = [];
        }
        this.pageRequest.params = {
          sku: this.filters.sku,
          shop: this.filters.shop,
          goodsType: this.filters.goodsType,
          fromTradeDate: this.filters.tradeDateRange.length >= 1 ? this.filters.tradeDateRange[0] : '',
          toTradeDate: this.filters.tradeDateRange.length === 2 ? this.filters.tradeDateRange[1] : '',
        };

        this.$api.revenue.goodsFindPage(this.pageRequest).then((res) => {
          if (res.code === 200) {
            this.pageResult = res.data;
          }
        }).then((data !== null && typeof data !== 'undefined') ? data.callback : '');
      },
      //导出数据
      exportGoodsRevenue() {
        this.pageRequest.params = {
          sku: this.filters.sku,
          shop: this.filters.shop,
          fromTradeDate: this.filters.tradeDateRange.length >= 1 ? this.filters.tradeDateRange[0] : '',
          toTradeDate: this.filters.tradeDateRange.length === 2 ? this.filters.tradeDateRange[1] : '',
        };
        try {
          this.$api.revenue.goodsRevenueExport(this.pageRequest).then((res) => {
            this.$alert(res.data, '导出成功', {
              confirmButtonText: '确定',
              callback: action => {
              }
            })
          })
        } catch (e) {
          console.error(e);
        }
      },
      //重置搜索条件
      reset() {
        this.$refs['filters'].resetFields();
        this.findPage();
      },
      //获取店铺信息
      findShops() {
        this.shops = localStorage.getItem('authorizedShops').split(',');
      },
      findGoodsType() {
        this.$api.dict.findByType({type: 'goods_type'}).then((res) => {
          if (res.code === 200) {
            this.goodsTypes = res.data;
          }
        })
      },
      getLastMonthFirstAndLastDay() {
        let nowDays = new Date();
        let year = nowDays.getFullYear();
        let month = nowDays.getMonth();
        if (month === 0) {
          month = 12;
          year = year - 1;

        }
        if (month < 10) {
          month = '0' + month;
        }

        let myDate = new Date(year, month, 0);
        let startDate = year + '-' + month + '-01';
        let endDate = year + '-' + month + '-' + myDate.getDate();
        this.filters.tradeDateRange.push(startDate, endDate);
      }
    },
    mounted() {
      this.initColumns();
      this.findShops();
      this.findGoodsType();
    },
    //初始化搜索条件
    created() {
      this.getLastMonthFirstAndLastDay();
    }
  }
</script>

<style scoped>

</style>
